package com.facefun.util;

import java.io.File;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

public class FileUploadUtil {

	private static String url="/upload";
	
	public static String upload(MultipartFile file,HttpServletRequest request){
		if(file.getSize()==0 || file==null){
			throw new RuntimeException("上传文件不能为空");
		}

		String fileName=file.getOriginalFilename();
		StringBuffer sb=new StringBuffer(request.getServletContext().getRealPath(url));
		StringBuffer finalName=new StringBuffer();
		finalName.append(System.currentTimeMillis()).append(new Random().nextInt(1000)).append(fileName.substring(fileName.lastIndexOf(".")));
		try {
			sb.append(File.separator).append(finalName);
			file.transferTo(new File(sb.toString()));
		} catch (Exception e) {
			throw new RuntimeException("文件上传失败！");
		}
		sb=new StringBuffer(url);
		sb.append("/").append(finalName);
		return sb.toString();
	}
	
	public static String uploadUpdate(MultipartFile file,String oldPath,HttpServletRequest request){
		uploadDelete(oldPath, request);
		
		return upload(file,request);
	}

	public static void uploadDelete(String oldPath,HttpServletRequest request){
		if(oldPath!=null && !oldPath.startsWith("http") ){
			File f=new File(request.getServletContext().getRealPath(oldPath));
			if(f.exists()){
				f.delete();
			}
		}
	}
}
